package com.yan.yanbi.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.Scanner;

/**
 * direct交换机生产者代码
 *
 * @author 86177
 */
public class DirectProducer {

    private static final String DIRECT_EXCHANGER = "direct-exchange";

    public static void main(String[] argv) throws Exception {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();

        // 设置 rabbitmq 对应的信息
        factory.setHost("47.109.81.239");
        factory.setUsername("yhnyhn123");
        factory.setPassword("1658450511");

        //建立连接并创建通道
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            //使用通道声明交换机，类型为direct
            channel.exchangeDeclare(DIRECT_EXCHANGER, "direct");

            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String userInput = scanner.nextLine();
                String[] splits = userInput.split(" ");
                if (splits.length < 1) {
                    continue;
                }
                //获取输入的路由键和消息
                String message = splits[0];
                String routingKey = splits[1];
                //发布消息到交换机，并指明routingKey
                channel.basicPublish(DIRECT_EXCHANGER, routingKey, null, message.getBytes("UTF-8"));
                System.out.println(" [x] Sent '" + message + " with routing " + routingKey + "'");
            }
        }
    }
}
